package com.xq.shop.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xq.shop.po.Menu;
import com.xq.shop.service.admin.IBaseService;
import com.xq.shop.service.admin.IMenuService;
import com.xq.shop.util.AdminServiceFactory;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("/admin/")
public class MenuController extends BaseController<Menu>{

	IMenuService menuService = AdminServiceFactory.getMenuService();
	
	@Override
	public IBaseService<Menu> getService() {
		return menuService;
	}
	
	@RequestMapping("menu_delete.do")
	public void delete(String id, HttpServletResponse response){
		
		super.delete(id, response);
	}
	
	@RequestMapping("menu_edit.do")
	public ModelAndView edit(String id){
		
		ModelAndView modelAndView = new ModelAndView("admin/setting/menu_edit");
		Menu menu;
		if(id != null){
			menu = menuService.get(Long.parseLong(id));
		} else {
			menu = new Menu();
		}
		
		if(menu == null){
			//TODO goto 404
			return modelAndView;
		} else {
			List<Menu> menuList = new ArrayList<Menu>();
			Menu tmp = new Menu();
			tmp.setName("顶级菜单");
			tmp.setId(0L);
			menuList.add(tmp);
			menuList.addAll(menuService.getByPID(0L));
			modelAndView.addObject(menu);
			modelAndView.addObject(menuList);
			return modelAndView;
		}
	}
	
	@RequestMapping("menu_list.do")
	@ResponseBody
	public String list(SearchObject search){
		return GsonUtil.toJson(menuService.get(search));
	}
	
	@RequestMapping("menu_save.do")
	public ModelAndView save(Menu menu, HttpServletResponse response){
		
		menuService.saveOrUpdate(menu);
		ModelAndView modelAndView = new ModelAndView("admin/setting/menu_list");
		modelAndView.addObject(new RespMsg(Result.success, "保存成功"));
		return modelAndView;
	}
}
